package com.ganbo.giteelogin.controller;

import com.ganbo.giteelogin.access_token.ProviderToken;
import com.ganbo.giteelogin.model.GiteeUser;
import com.ganbo.giteelogin.provider.GiteeProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AccessTokenController {

    @Autowired
    private GiteeProvider giteeProvider;

    @Value("${client_id}")
    private String clientId;

    @Value("${redirect_uri}")
    private String redirectUri;

    @Value("${client_secret}")
    private String clientSecret;

    @GetMapping("/callback")
    public String callback(@RequestParam("code") String code,
                           @RequestParam("state") String state,
                           Model model) {
        //用户授权信息
        ProviderToken token = new ProviderToken();
        token.setClientId(clientId);
        token.setRedirectUri(redirectUri);
        token.setClientSecret(clientSecret);
        token.setCode(code);
        token.setState(state);
        //获取token和登录的用户信息
        String accessToken = giteeProvider.getGiteeToken(token);
        GiteeUser giteeUser = giteeProvider.getGiteeUser(accessToken);
        model.addAttribute("user", giteeUser);
        model.addAttribute("name", giteeUser.getName());
        System.out.println(giteeUser);
        return "success";
    }
}
